LEÇON 3

Fonctions Avancées et Modules Python

Arguments, Portée des Variables, Lambda et Modules Standard

Français - Fonctions Avancées

1. Arguments de Fonctions

Python offre plusieurs façons de passer des arguments aux fonctions.

# Arguments positionnels et par mot-clé
def decrire_personne(nom, age, ville="Paris"):
    return f"{nom} a {age} ans et habite à {ville}"

# Appels différents
print(decrire_personne("Alice", 25)) # Argument par défaut utilisé
print(decrire_personne("Bob", 30, "Lyon")) # Tous les arguments fournis
print(decrire_personne(age=22, nom="Claire")) # Arguments par mot-clé
# *args pour un nombre variable d'arguments
def somme(*args):
    total = 0
    for nombre in args:
        total += nombre
    return total

print(somme(1, 2, 3)) # 6
print(somme(10, 20, 30, 40)) # 100

# **kwargs pour arguments nommés variables
def afficher_info(**kwargs):
    for cle, valeur in kwargs.items():
        print(f"{cle}: {valeur}")

afficher_info(nom="Alice", age=25, ville="Paris")

2. Portée des Variables (Scope)

Comprendre la portée des variables est crucial pour éviter les erreurs.

# Variables globales et locales
variable_globale = "Je suis globale"

def ma_fonction():
    variable_locale = "Je suis locale"
    print(variable_locale) # OK
    print(variable_globale) # OK - lecture

# Pour modifier une variable globale
    global variable_globale
    variable_globale = "Modifiée dans la fonction"

ma_fonction()
print(variable_globale) # Affiche la valeur modifiée
# print(variable_locale) # ERREUR - variable_locale n'existe pas ici
Astuce : Évitez d'utiliser trop de variables globales. Privilégiez le passage d'arguments et les retours de fonctions.

3. Fonctions Lambda

Les fonctions lambda sont des fonctions anonymes à une seule expression.

# Fonction lambda simple
carre = lambda x: x ** 2
print(carre(5)) # 25

# Lambda avec plusieurs paramètres
addition = lambda a, b: a + b
print(addition(10, 20)) # 30

# Utilisation avec map()
nombres = [1, 2, 3, 4, 5]
carres = list(map(lambda x: x**2, nombres))
print(carres) # [1, 4, 9, 16, 25]

# Utilisation avec filter()
pairs = list(filter(lambda x: x % 2 == 0, nombres))
print(pairs) # [2, 4]

4. Modules Python Standard

Python inclut de nombreux modules utiles "batteries included".

# Module math
import math

print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(math.factorial(5)) # 120

# Module random
import random

print(random.randint(1, 100)) # Nombre aléatoire entre 1 et 100
print(random.choice(["pomme", "banane", "orange"]))

# Module datetime
import datetime

maintenant = datetime.datetime.now()
print("Date et heure actuelles:", maintenant)
print("Année:", maintenant.year)
print("Mois:", maintenant.month)
Important : N'utilisez pas from module import * car cela peut créer des conflits de noms. Préférez import module ou from module import fonction_specifique.

English - Advanced Functions and Modules

1. Function Arguments

Python offers several ways to pass arguments to functions.

# Positional and keyword arguments
def describe_person(name, age, city="Paris"):
    return f"{name} is {age} years old and lives in {city}"

# Different calls
print(describe_person("Alice", 25)) # Default argument used
print(describe_person("Bob", 30, "Lyon")) # All arguments provided
print(describe_person(age=22, name="Claire")) # Keyword arguments
# *args for variable number of arguments
def sum_all(*args):
    total = 0
    for number in args:
        total += number
    return total

print(sum_all(1, 2, 3)) # 6
print(sum_all(10, 20, 30, 40)) # 100

# **kwargs for variable keyword arguments
def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=25, city="Paris")

2. Variable Scope

Understanding variable scope is crucial to avoid errors.

# Global and local variables
global_variable = "I am global"

def my_function():
    local_variable = "I am local"
    print(local_variable) # OK
    print(global_variable) # OK - reading

# To modify a global variable
    global global_variable
    global_variable = "Modified in function"

my_function()
print(global_variable) # Shows modified value
# print(local_variable) # ERROR - local_variable doesn't exist here
Tip: Avoid using too many global variables. Prefer passing arguments and function returns.

3. Lambda Functions

Lambda functions are anonymous, single-expression functions.

# Simple lambda function
square = lambda x: x ** 2
print(square(5)) # 25

# Lambda with multiple parameters
add = lambda a, b: a + b
print(add(10, 20)) # 30

# Using with map()
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16, 25]

# Using with filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]

4. Python Standard Modules

Python includes many useful modules "batteries included".

# math module
import math

print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(math.factorial(5)) # 120

# random module
import random

print(random.randint(1, 100)) # Random number between 1 and 100
print(random.choice(["apple", "banana", "orange"]))

# datetime module
import datetime

now = datetime.datetime.now()
print("Current date and time:", now)
print("Year:", now.year)
print("Month:", now.month)
Important: Don't use from module import * as it can create name conflicts. Prefer import module or from module import specific_function.